<?php

namespace App\Jobs;

use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use App\Services\CloseUnpaidStorm\CloseUnpaidStorm;
use Illuminate\Support\Facades\Redis;
use App\Models\GoldRecord;
use Illuminate\Support\Facades\DB;
use Rainsens\Dinglog\Facades\Dinglog;


class CheckGoldRecordJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected int $uid;
    protected string $unpaidCacheId;

    public function __construct()
    {

    }

	public function handle()
    {

        Dinglog::text("执行刷单任务");
       $result = GoldRecord::query()
               ->select("id","gold_product_id")
               ->whereDate("created_at",Carbon::today())
               ->groupBy("gold_product_id")
               ->whereNull('closed_at')
               ->having(DB::raw('COUNT(gold_product_id)'),'>',1)
               ->get()->toArray();

       if($result){
            foreach($result as $k=>$v){
                $records = GoldRecord::query()
                    ->leftjoin('gold_pay_records','gold_records.id','=','gold_pay_records.gold_record_id')
                    ->select("gold_records.*")
                    ->whereDate("gold_records.created_at",Carbon::today())
                    ->whereNull("voucher")
                    ->where("is_del",false)
                    ->where('gold_records.gold_product_id',$v['gold_product_id'])->whereNull('gold_records.paid_at')->get();

                if($records->count() > 1){
                    foreach($records as $k=>$record){
                        if($k!=0){
                            $beans = $record->pay_gold_beans;
                            $data = ['gold_record_id' => $record->id];
                            account_beans($record->user)->plusExtraGoldBeans($beans, $data);
                            $record->user->delRecordFromUnpaidCache($record->cache_id);
                            $record->update(["is_del"=>true]);
                        }

                    }

                }else{
                    foreach($records as $k=>$record){
                            $beans = $record->pay_gold_beans;
                            $data = ['gold_record_id' => $record->id];
                            account_beans($record->user)->plusExtraGoldBeans($beans, $data);
                            $record->user->delRecordFromUnpaidCache($record->cache_id);
                            $record->update(["is_del"=>true]);

                    }


                }
                

            }

       }
    }
}
